
export default async function distance(lng,lat) {
    try {
        const db = uniCloud.databaseForJQL();
        const res = await db.collection('opendb-poi').aggregate().geoNear({
            distanceField: 'distance',
            spherical: true,
            near: new db.Geo.Point(lng,lat),
            maxDistance: 30000
        }).end();
        return res;
    } catch (e) {
        return {
            success: false,
            error: e.message
        };
    }
}
export function formatDistance(location,item) {


		if(Object.keys(item).length===0||!location){
		return
	}

	let  lat1=item.content.senderLocation.latitude
	let  lon1=item.content.senderLocation.longitude
	let  lon2=location.longitude
	let  lat2=location.latitude


const dis = meDistance(lat1, lon1, lat2, lon2)	

    if (dis===undefined){
		return ""
	}
    if (dis < 0.1) {
        return "附近";
    } else {
        // 将距离从米转换为公里
        const distanceInKm = dis;
        // 保留一位小数
        return distanceInKm.toFixed(1) + "公里";
    }
}

function meDistance(lat1, lon1, lat2, lon2) {
    // 将角度转换为弧度
    const toRadians = (degrees) => degrees * (Math.PI / 180);

    // 地球的平均半径，单位：千米
    const R = 6371; 

    // 将纬度和经度转换为弧度
    const dLat = toRadians(lat2 - lat1);
    const dLon = toRadians(lon2 - lon1);

    // 计算纬度和经度的半正矢
    const a =
        Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(toRadians(lat1)) * Math.cos(toRadians(lat2)) *
        Math.sin(dLon / 2) * Math.sin(dLon / 2);

    // 计算中心角
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

    // 计算距离
    const distance = R * c;
	
     return distance;
}
export function distance_m(loc1,loc2){
   
		const lon1=loc1.longitude
		const lat1=loc1.latitude
		const lon2=loc2.longitude
		const lat2=loc2.latitude
	
	const dis = meDistance(lat1, lon1, lat2, lon2)
	    if (dis===undefined){
			return ""
		}
	    if (dis < 1) {
	     return `${Math.floor(dis*1000)}米`
	    } else{
	      return dis.toFixed(1) + "公里";
	    }
	
}
export function distanceNum(loc1,loc2){
	const lon1=loc1.longitude
	const lat1=loc1.latitude
	const lon2=loc2.longitude
	const lat2=loc2.latitude
	
	
	const dis = meDistance(lat1, lon1, lat2, lon2)
	    if (dis===undefined){
			return ""
		}else{ return dis}
	
}

